package com.qf.commons.event.apply.producer;


import com.qf.commons.core.utils.ApplicationUtils;
import com.qf.commons.event.core.standrad.ProduceStandrad;
import com.qf.commons.event.entity.QphoneMessage;

import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 发布端的工具类
 * description:
 * author: Ken
 * 公众号：Java架构栈
 */
public class EventUtils {

    private static ProduceStandrad produceStandrad;

    static {
        //从ioc容器中获取当前类型的Bean
        produceStandrad = ApplicationUtils.getBean(ProduceStandrad.class);
    }

    /**
     * 发送迅捷事件  Kafka实时性 比RabbitMQ弱   Kafka批量发送
     * @param eventType
     * @param eventContent
     * @param <T>
     */
    public static <T> void send(String eventType, T eventContent){
        sendEvent(eventType, eventContent, 0, -1, null);
    }

    /**
     * 发送延迟消息
     * @param <T>
     */
    public static <T> void sendDelay(String eventType, T eventContent, long delay, TimeUnit unit){
        sendEvent(eventType, eventContent, 0, delay, unit);
    }

    /**
     * 私有方法 - 发送消息
     * msgType - 0 - 迅捷 1 - 可靠性
     * @param <T>
     */
    private static <T> void sendEvent(String eventType, T eventConent, int msgType, long delay, TimeUnit unit){
        //构建Messsage对象
        QphoneMessage message = new QphoneMessage.Builder(eventType, eventConent)
                .setMsgId(UUID.randomUUID().toString())
                .setMsgType(msgType)
                .setDelayMs(delay == -1 ? -1 : unit.toMillis(delay))
                .setSendTime(new Date())
                .build();

        //调用下层，发送QphoneMessage对象
        produceStandrad.sendMessage(message);
    }

}
